﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Jhong.FunMVC
{
    internal class ControllerFactory
    {
        private static IDictionary<string, Type> _controllersList;

        static ControllerFactory()
        {
            _controllersList = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
            var controlBase = typeof(Controller);
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var type in assembly.GetTypes())
                {
                    Type baseType = type.BaseType;
                    while (true)
                    {
                        if (null == baseType) break;
                        if (baseType == controlBase)
                        {
                            _controllersList.Add(type.Name, type);
                            break;
                        }
                        baseType = baseType.BaseType;
                    }
                }
            }
        }


        public static void CreateControllerInstance(ref ControllerContext context)
        {
            if (string.IsNullOrWhiteSpace(context.Request.Controller)) context.Request.Controller = context.RouteBase.Defaults.GetType().GetProperty("controller").GetValue(context.RouteBase.Defaults) as string;
            var controllerTypeName = context.Request.Controller + "Controller";
            if (false == _controllersList.Keys.Contains(controllerTypeName)) return;
            context.ControllerType = _controllersList[controllerTypeName];
            context.Controller = Activator.CreateInstance(context.ControllerType) as Controller;
            context.Controller.Request = context.Request;
            context.Controller.Response = context.Response;
        }

    }
}
